package com.onenine.app.activity;

import android.content.Context;
import android.content.Intent;
import android.util.SparseIntArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayout;
import com.onenine.app.R;
import com.onenine.app.event.SelectedLabelEvent;
import com.onenine.app.model.LabelItem;
import com.onenine.app.request.GetLabelsRequest;
import com.onenine.app.response.GetLabelsResponse;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.base.BaseActivity;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.Toasty;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.SizeUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 选择三种标签
 */
public class SelectLabelsActivity extends BaseActivity {

    private static final int MAX_TYPE_COUNT = 3;
    private FlexboxLayout mFbSelect, mFbLabel, mFbObject, mFbHobby;
    private List<LabelItem> mSelectedList;
    private SparseIntArray mCountArray = new SparseIntArray();

    public static void launchActivity(Context context, List<LabelItem> labelList) {
        Intent intent = new Intent(context, SelectLabelsActivity.class);
        intent.putExtra("data", (Serializable) labelList);
        context.startActivity(intent);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_select_three_labels;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mToolbar.setCenterTitle(R.string.my_label);
        mToolbar.setRightTitle(R.string.save);
        mToolbar.setRightTitleColor(RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR));
        mFbSelect = findViewById(R.id.fb_select_already);
        mFbLabel = findViewById(R.id.fb_my_label);
        mFbObject = findViewById(R.id.fb_my_object);
        mFbHobby = findViewById(R.id.fb_my_hobby);
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mToolbar.setOnRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectedList.isEmpty()) {
                    Toasty.showNormal(R.string.label_unselected_hint);
                    return;
                }
                EventBus.getDefault().post(new SelectedLabelEvent(mSelectedList));
                finish();
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        initSelectedLabels();
        getLabelsByType(DataType.MY_LABEL);
        getLabelsByType(DataType.MY_OBJECT);
        getLabelsByType(DataType.MY_HOBBY);
    }

    /**
     * 初始化已选择标签
     */
    private void initSelectedLabels() {
        mSelectedList = (List<LabelItem>) getIntent()
                .getSerializableExtra("data");
        if (mSelectedList == null) {
            mSelectedList = new ArrayList<>();
        } else {
            for (LabelItem labelItem : mSelectedList) {
                addSelectedLabel(labelItem);
            }
        }
    }

    /**
     * 拉取标签列表
     */
    private void getLabelsByType(final int type) {
        GetLabelsRequest request = new GetLabelsRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setLabelType(type);
        OkRequest.getInstance().withUrl(UrlConfig.QUERY_LABEL)
                .withRequest(request).doRequest(NearbyConditionActivity.class.getSimpleName(), new OkCallback<GetLabelsResponse>() {
            @Override
            public void onResponse(GetLabelsResponse response, String srcData) {
                if (response.isSuccess()) {
                    switch (type) {
                        case DataType.MY_LABEL:
                            showUnSelectedLabels(mFbLabel, response.getLabelItemList());
                            break;
                        case DataType.MY_OBJECT:
                            showUnSelectedLabels(mFbObject, response.getLabelItemList());
                            break;
                        case DataType.MY_HOBBY:
                            showUnSelectedLabels(mFbHobby, response.getLabelItemList());
                            break;
                    }
                }
            }
        });
    }

    /**
     * 增加选择的标签
     *
     * @param labelItem
     */
    private boolean addSelectedLabel(final LabelItem labelItem) {
        int typeCount = mCountArray.get(labelItem.getType());
        if (typeCount >= MAX_TYPE_COUNT) {
            Toasty.showNormal(R.string.label_type_max_count_limit);
            return false;
        }
        mCountArray.put(labelItem.getType(), ++typeCount);
        int labelMargin = SizeUtils.dp2px(10);
        TextView tvLabel = (TextView) getLayoutInflater().inflate(R.layout.layout_label_item, null, false);
        tvLabel.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_BG));
        tvLabel.setText(labelItem.getLabelName());
        tvLabel.setTextColor(RoleResLoader.getRoleColorStateList(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_TEXT_BG));
        tvLabel.setSelected(true);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout
                .LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(labelMargin, labelMargin, labelMargin, labelMargin);
        mFbSelect.addView(tvLabel, -1, layoutParams);
        tvLabel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelectedList.remove(labelItem);
                mFbSelect.removeView(v);
                mCountArray.put(labelItem.getType(), mCountArray
                        .get(labelItem.getType()) - 1);
            }
        });
        return true;
    }

    /**
     * 显示标签
     *
     * @param flexboxLayout
     * @param labelList
     */
    private void showUnSelectedLabels(final FlexboxLayout flexboxLayout, List<LabelItem> labelList) {
        final int labelMargin = SizeUtils.dp2px(10);
        for (final LabelItem label : labelList) {
            TextView tvLabel = (TextView) getLayoutInflater().inflate(R.layout.layout_label_item, null, false);
            tvLabel.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_BG));
            tvLabel.setText(label.getLabelName());
            tvLabel.setTextColor(RoleResLoader.getRoleColorStateList(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_TEXT_BG));
            tvLabel.setSelected(false);
            FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout
                    .LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(labelMargin, labelMargin, labelMargin, labelMargin);
            flexboxLayout.addView(tvLabel, -1, layoutParams);
            tvLabel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    label.setType(mFbLabel == flexboxLayout ? DataType.MY_LABEL
                            : mFbObject == flexboxLayout ? DataType.MY_OBJECT : DataType.MY_HOBBY);
                    if (!mSelectedList.contains(label)) {
                        if (addSelectedLabel(label)) {
                            mSelectedList.add(label);
                        }
                    }
                }
            });
        }
    }

}
